//
//  ShapeVC.m
//  Imagedemo
//
//  Created by 文杰 许                       on 2018/3/30.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

#import "ShapeVC.h"

@interface ShapeVC ()

@end

@implementation ShapeVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //创建CGContextRef
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //创建CGMutablePathRef
    CGMutablePathRef pathRef = CGPathCreateMutable();
    
    //绘制path
    CGRect rect = CGRectInset(self.view.bounds, 0, 100);
    CGPathMoveToPoint(pathRef, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMinX(rect), CGRectGetMidY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetWidth(rect), CGRectGetMidY(rect));
    CGPathCloseSubpath(pathRef);
    
    //绘制渐变
    [self drawLinearGradient:context path:pathRef startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
    
    CGPathRelease(pathRef);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imgV = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imgV];
}

- (void)drawLinearGradient:(CGContextRef)context
                      path:(CGPathRef)path
                startColor:(CGColorRef)startColor
                  endColor:(CGColorRef)endColor
{
    CGColorSpaceRef colorRef = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = {0.0, 1.0};
    NSArray *colors = @[(__bridge id)startColor, (__bridge id)endColor];
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorRef, (__bridge CFArrayRef)colors, locations);
    
    CGRect rect = CGPathGetBoundingBox(path);
    
    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation);
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorRef);
}

@end
